package cn.bob.filter;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.core.Ordered;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Date;
import java.util.List;
import java.util.logging.Logger;

/**
 * @desc 自定义gateway局部过滤器
 * @author bob
 * @data 2022/11/13-16:01
 */
public class springcloudGatewayFilter implements GatewayFilter, Ordered {
    //log原生打印
    private static final Log log= LogFactory.getLog(springcloudGatewayFilter.class);

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        log.info(" run pay path:"+exchange.getRequest().getURI().getPath());
        //获取开始运行时间
        exchange.getAttributes().put("gatewayTime",new Date().getTime());
        //回调方法  过滤器 执行完成到服务  再通过then回调执行
        return chain.filter(exchange).then(
                Mono.fromRunnable(() -> {
                    //开始时间
                    Long startTime = exchange.getAttribute("gatewayTime");
                    //结束时间
                    Long endTime=(System.currentTimeMillis() - startTime);
                    if (startTime != null) {
                        log.info(exchange.getRequest().getURI().getRawPath() + ": " + endTime + "ms");
                    }
                })
        );
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
